package com.edu.zhku.wms.config;

import com.edu.zhku.wms.common.Consts;
import com.edu.zhku.wms.service.UserPrincipalService;
import com.edu.zhku.wms.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Feng
 * @since 2021/10/28 14:13
 */
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UserPrincipalService userPrincipalService;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader(Consts.REQ_JWT_HEADER_KEY);
        if (authHeader != null && authHeader.startsWith(Consts.REQ_JWT_HEADER_VALUE_PREFIX)) {
            String authToken = authHeader.substring(Consts.REQ_JWT_HEADER_VALUE_PREFIX.length());// The part after "Bearer "
            String username = null;
            try {
                username = jwtUtil.getUsernameFromJWT(authToken);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = null;
                try {
                    userDetails = userPrincipalService.loadUserByUsername(username);
                } catch (UsernameNotFoundException e) {
                    logger.error(e.getMessage());
                }
                if (userDetails != null && jwtUtil.validateToken(authToken, userDetails)) {
                    jwtUtil.checkRenewal(username);
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }
}
